package com.reger.l2cache.pipeline.core;

import java.util.concurrent.CountDownLatch;

import org.springframework.data.redis.connection.RedisConnection;

public class QueueNode<T> {

	private CountDownLatch downLatch = new CountDownLatch(1);
	private Operations operations;
	private Callback<T> callback;
	private Object relust;
	private Exception exception;

	public QueueNode(Operations operations, Callback<T> callback) {
		super();
		this.operations = operations;
		this.callback = callback;
	}

	public QueueNode<T> await() {
		try {
			downLatch.await();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		return this;
	}

	public QueueNode<T> aNotify() {
		downLatch.countDown();
		return this;
	}

	public QueueNode<T> operation(RedisConnection connection) {
		try {
			this.relust = operations.operation(connection);
		} catch (Exception exception) {
			this.exception = exception;
		}
		return this;
	}

	public QueueNode<T> callback(Object relust) {
		this.relust = relust;
		return this;
	}

	public QueueNode<T> callback(Exception exception) {
		this.exception = exception;
		return this;
	}

	public T relust() {
		if (this.exception != null) {
			if (this.exception instanceof RuntimeException) {
				throw (RuntimeException) this.exception;
			}
			throw new RuntimeException(this.exception);
		}
		return callback.callback(this.relust);
	}
}